<template>
  <div class="bg-white">
    <Card>
      <Table
        sticky
        :bordered="true"
        :dataSource="dataSource"
        :columns="appMgtColumns"
        :pagination="false"
        :loading="loading"
        :scroll="scroll"
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'name'">
            <span v-per="'detail'"
              ><a @click="detail(record)"><Avatar :src="record.logoLink" alt="xxx" />{{ ' ' + text }}</a></span
            >
          </template>
          <template v-if="column.dataIndex === 'action'">
            <span v-per="'subscribe'" v-if="!record.isSubscribed && record.type == 3">
              <a @click="subsc(record)">订阅</a>
            </span>

            <span v-per="'renew'" v-if="record.isSubscribed && record.type == 3 && record.paymentType == 'prePaid'">
              <a @click="renew(record)">续订</a>
              <Divider v-if="record.isSubscribed && record.type == 3" type="vertical" />
            </span>

            <span v-per="'subscribeDetail'" v-if="record.isSubscribed">
              <a @click="subDetail(record)">订阅详情</a><Divider v-if="record.isSubscribed" type="vertical"
            /></span>

            <span v-per="'unsubscribe'" v-if="record.isSubscribed">
              <a @click="showUnsubscribe(record)">退订</a><Divider type="vertical" v-if="record.isSubscribed"
            /></span>

            <Dropdown v-if="record.isSubscribed">
              <a class="ant-dropdown-link" @click.prevent>
                <MoreOutlined />
              </a>
              <template #overlay>
                <Menu>
                  <MenuItem>
                    <span v-per="'appAuth'"> <a @click="openModal(record)">应用授权</a></span>
                  </MenuItem>
                  <MenuItem>
                    <span v-per="'fileSystemMgmt'"
                      ><a @click="fileSystemManage(record)" v-if="record.ifSupportFileSystem">文件系统管理</a></span
                    >
                  </MenuItem>
                </Menu>
              </template>
            </Dropdown>
          </template>
        </template>
      </Table>
      <br />
      <Pagination
        show-size-changer
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="total"
        :show-total="(total) => `共 ${total} 条`"
        @showSizeChange="onShowSizeChange"
      />
      <FileDrawer :modelId="appId" ref="drawerRef"></FileDrawer>
      <RenewModal ref="renewModal" @submitSuccess="getDataSource" />
      <Modal
        ref="modalRef"
        v-model:visible="showModal"
        :centered="false"
        :width="650"
        :destroyOnClose="true"
        cancelText="取消"
        okText="确认"
        title="授权人员管理"
        @ok="handleSubmit"
      >
        <AuthorizedModal ref="authModelRef" :appId="appId" :subAppId="subAppId"></AuthorizedModal>
      </Modal>
      <AppInfoDrawer ref="appInfoDrawer" :appId="appId" />
      <SubscribeDetail ref="subscDetail" />
      <ManageDn ref="mgDn" />
    </Card>
  </div>
</template>
<script lang="ts" setup>
import { createVNode, nextTick, ref, watch } from 'vue';
import { MoreOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import FileDrawer from '/@/views/system-mgmt/appfs-mgmt/fileSystemDrawer.vue';
import RenewModal from '/@/views/tenant-center/enterpriseAppManagement/component/RenewModal.vue';
import AuthorizedModal from '/@/views/system-mgmt/authorization-mgmt/authorizedModal.vue';
import AppInfoDrawer from '/@/views/system-mgmt/app-mgmt/drawer/appInfo.vue';
import { Card, Table, Dropdown, Pagination, Menu, MenuItem, Divider, message, Avatar, Modal } from 'ant-design-vue';
import { appMgtColumns } from './data';
import { releaseApp } from '/@/api/deployment-center/deployTask';
import { useUserStoreWithout } from '/@/store/modules/user';
import { getSubAppList, updateAppAuth } from '/@/api/system-mgmt/app-mgmt/app';
import { RoleRelation, SubAppInfo } from '/@/api/system-mgmt/app-mgmt/model/appModel';
import { useAuthState } from '../authorization-mgmt/auth';
import { useMessage } from '/@/hooks/web/useMessage';
import SubscribeDetail from '/@/views/system-mgmt/tenant-app-mgmt/component/SubscribeDetail.vue';
import ManageDn from '/@/views/system-mgmt/tenant-app-mgmt/component/ManageDn.vue';
import { getAppTemplate } from '/@/api/system-mgmt/tenant-app-mgmt/tenantApp';
import { router } from '/@/router';
const loading = ref(true);
const { createMessage } = useMessage();
const { getRoleMap } = useAuthState();
const scroll = ref<undefined | object>(undefined);
let dataSource = ref();
let appId = ref<string>('');
let current = ref(1);
const total = ref<number>(0);
const pageSize = ref(10);

const getDataSource = async () => {
  try {
    let data = await getAppTemplate();
    dataSource.value = data.slice((current.value - 1) * pageSize.value, current.value * pageSize.value);
    total.value = data.length;
  } finally {
    loading.value = false;
  }
};
getDataSource();
const onShowSizeChange = () => {
  getDataSource();
};
watch(current, () => {
  getDataSource();
});

const renewModal = ref();
const renew = (record) => {
  renewModal.value.openRenew(record);
};

let appList = ref<SubAppInfo[]>();
const userStore = useUserStoreWithout();
const tenantCode = userStore.getUserInfo.tenantCode;
const getAppInfo = async function getSubAppListInfo() {
  appList.value = await getSubAppList();
};
const showUnsubscribe = (record) => {
  Modal.confirm({
    title: '是否取消订阅此应用?',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { style: 'color:red;' }, `即将退订（${record.name}）此次操作不可回退`),
    async onOk() {
      const res = await releaseApp({ appId: String(record.appId), tenantCode });
      message.success('取消订阅成功');

      // logout when there is no app after unsubscribing
      if (!res.hasRemainedApp) {
        userStore.logout(true);
      } else {
        await getAppInfo();
      }
    },
    class: 'test',
  });
};

const subscDetail = ref();
const subDetail = (record) => {
  subscDetail.value.openDetail(record);
};

let showModal = ref<boolean>(false);
let subAppId = ref<string>('');
let authModelRef = ref();
function openModal(record) {
  appId.value = String(record.appId);
  subAppId.value = String(record.subAppId);
  showModal.value = true;
}
const handleSubmit = async () => {
  let roleMap: RoleRelation[] = [];
  getRoleMap().forEach((value, key) => {
    let temp: string[] = [];
    value.forEach((item) => {
      temp.push(item);
    });
    roleMap.push({ userId: key, roleIdList: temp });
  });

  await updateAppAuth({ appId: appId.value, appAuthForUsers: roleMap });
  createMessage.success('修改授权信息成功');
  showModal.value = false;
};

const drawerRef = ref();

const fileSystemManage = async (record) => {
  appId.value = String(record.appId);
  nextTick(async () => {
    await drawerRef.value.openDrawer();
  });
};

const appInfoDrawer = ref();
const detail = (record) => {
  appId.value = String(record.appId);
  nextTick(async () => {
    await appInfoDrawer.value.openDrawer();
  });
};

const subsc = (record) => {
  router.push({
    path: '/instancePurchase',
    query: {
      type: 'tenant',
      appId: String(record.appId),
      appName: record.name,
    },
  });
};
</script>
<style lang="less">
.ant-pagination {
  float: right;
}
.btn-wrapper {
  float: right;
}
</style>
